package logic

import (
	"context"
	"fmt"
	"shell/houserpc/houserpc"
	"shell/houserpc/internal/svc"
	"shell/models/cache"
	"shell/models/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPasswordLogic) ForgetPassword(in *houserpc.ForgetPasswordRequest) (*houserpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if in.Mobile != "" {
		result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Mobile).Result()
		if result == "" {
			return nil, fmt.Errorf("短信验证码为空,请前去发送")
		}
		if result != in.SendSmsCode {
			return nil, fmt.Errorf("短信验证码错误,请重新输入")
		}
		mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
		if in.Password != in.NewPassword {
			return nil, fmt.Errorf("两次密码输入不一致,请重新输入")
		}
		if in.Password == user.Password {
			return nil, fmt.Errorf("新密码和旧密码一样,请重新输入")
		}
		user.Password = in.Password
	}
	mysql.DB.Debug().Updates(&user)
	return &houserpc.ForgetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
